package servlets;

import dao.JdbcRoleDao;
import dao.JdbcUserDao;
import entries.Role;
import entries.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;


public class AddUser extends Dispatcher {

    private final static Log LOGGER = LogFactory.getLog(AddUser.class);

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
                                                                              IOException {


        if (!(req.getParameter("password").equals(req.getParameter("passwordagain")))) {
            req.setAttribute("error", "passwords must be equal");
            this.forward("/newUser.jsp", req, resp);
            return;
        }

        JdbcUserDao userDao = new JdbcUserDao();

        User user = new User();
        user.setLogin(req.getParameter("login"));
        user.setPassword(req.getParameter("password"));
        user.setEmail(req.getParameter("email"));
        user.setFirstName(req.getParameter("firstname"));
        user.setLastName(req.getParameter("lastname"));
        user.setBirthDay(Date.valueOf(req.getParameter("birth")));

        JdbcRoleDao roleDao = new JdbcRoleDao();
        Role roleUser = roleDao.findByName(req.getParameter("role"));
        user.setRole(roleUser);

        try {
            userDao.create(user);
            List<User> list = userDao.findAll();
            req.setAttribute("users", list);
            this.forward("/adminPage.jsp", req, resp);
            return;
        } catch (SQLException e) {
            LOGGER.error("SQLException", e);
            throw  new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            LOGGER.error("ClassNotFoundException", e);
            throw  new RuntimeException(e);
        }
    }
}
